<?php

namespace App\Models;

use App\Models\Business\PlatformType;
use App\Models\Business\ShopProfileTemplate;
use App\Models\SubAccount\SubAccount;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ShopManager extends Model
{
    use HasFactory;
    protected $appends=['sub_account','renewal_account','customer_complaints'];
    protected $guarded = [];
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y/m/d H:i:s');
    }
    public function platForm(){
        return $this->hasOne(PlatformType::class,'id','plateform_id');
    }
    public function customer(){
        return $this->hasOne(CustomerManager::class,'id','customer_id');
    }
    public function template(){
        return $this->hasOne(ShopProfileTemplate::class,'id','template_id');
    }
    public function department(){
        return $this->hasOne(Department::class,'id','department_id');
    }
    public function detail(){
        return $this->hasMany(ShopManageDetail::class,'shop_manage_id','id');
    }

    //子账号数
    protected function subAccount(): Attribute
    {
        return new Attribute(
            get: fn () => $this->getAccount(),
        );
    }

    //7日内待续费数
    protected function renewalAccount(): Attribute
    {
        return new Attribute(
            get: fn () => $this->service(),
        );
    }
    //客诉数
    protected function customerComplaints(): Attribute
    {
        return new Attribute(
            get: fn () => $this->customers(),
        );
    }
    protected function service(){
        return SubAccount::query()
            ->where('shop_id',$this->attributes['id'])
            //结束时间<7天+当前时间
            ->where('service_time_end','<',now()->addDays(7))
            ->count();
    }

    protected function customers(){
        return CustomerComplaint::query()
            ->where('shop_id',$this->attributes['id'])
            ->count();
    }
    public function getAccount(){
        return SubAccount::query()
            ->where('shop_id',$this->attributes['id'])
            ->count();
    }

}
